# 修复LangChain导入警告，使用langchain_community
try:
    from langchain_community.chat_models import ChatOpenAI
except ImportError:
    # 降级处理，如果langchain_community不可用则使用旧版本导入
    from langchain.chat_models import ChatOpenAI

from langchain.tools import Tool
from langchain.schema import SystemMessage, HumanMessage
import json
from typing import Dict, Any
# 延迟导入MCP相关模块，避免循环导入
# from src.services.mcp_service import mcp_service_manager, MCPServiceError
# from src.config.settings import settings


def get_search_tool():
    """初始化并返回基于MCP的搜索工具"""
    
    def mcp_search(query: str) -> str:
        """使用MCP服务器执行搜索"""
        try:
            # 延迟导入MCP相关模块
            from src.services.mcp_service import mcp_service_manager, MCPServiceError
            from src.config.settings import settings
            
            # 检查是否有可用的search-server
            if settings.MCP_ENABLED and "search-server" in settings.MCP_SERVERS:
                if settings.is_mcp_server_enabled("search-server"):
                    # 尝试调用MCP search服务器的web_search工具
                    try:
                        result = mcp_service_manager.call_tool_sync(
                            "search-server", 
                            "web_search", 
                            {"query": query}
                        )
                        return json.dumps(result, ensure_ascii=False)
                    except MCPServiceError as e:
                        # 如果MCP调用失败，返回错误信息
                        return f"MCP搜索失败: {str(e)}"
            
            # 如果没有配置MCP或MCP调用失败，使用模拟结果
            return f"MCP搜索结果: {query}\n\n这是一个使用MCP服务器执行的搜索演示。搜索结果包含相关信息和分析。"
        except Exception as e:
            return f"搜索失败: {str(e)}"
    
    return Tool(
        name="mcp_web_search",
        description="使用MCP服务器执行网络搜索",
        func=mcp_search
    )


class MultimodalSearchTool:
    """多模态搜索工具类"""
    
    def __init__(self):
        """初始化多模态搜索工具"""
        self.name = "multimodal_search"
        self.description = "执行多模态搜索，包括文本、图像和表格数据"
    
    def _call_mcp_search(self, query: str) -> Dict[str, Any]:
        """
        调用MCP搜索服务器
        
        Args:
            query: 搜索查询
            
        Returns:
            搜索结果字典
        """
        try:
            # 延迟导入MCP相关模块
            from src.services.mcp_service import mcp_service_manager, MCPServiceError
            from src.config.settings import settings
            
            # 检查是否有可用的search-server
            if settings.MCP_ENABLED and "search-server" in settings.MCP_SERVERS:
                if settings.is_mcp_server_enabled("search-server"):
                    # 尝试调用MCP search服务器的web_search工具
                    try:
                        result = mcp_service_manager.call_tool_sync(
                            "search-server", 
                            "web_search", 
                            {"query": query}
                        )
                        return result
                    except MCPServiceError as e:
                        print(f"MCP搜索调用失败: {e}")
                        # 返回默认结构
                        return {
                            "text_results": f"MCP搜索失败: {str(e)}",
                            "images": [],
                            "tables": [],
                            "multimodal_content": {}
                        }
            
            # 如果没有配置MCP或MCP调用失败，返回模拟结果
            return {
                "text_results": f"模拟MCP搜索结果: {query}\n\n这是通过MCP服务器执行的搜索演示。",
                "images": [],
                "tables": [],
                "multimodal_content": {}
            }
        except Exception as e:
            print(f"搜索工具执行异常: {e}")
            return {
                "text_results": f"搜索工具异常: {str(e)}",
                "images": [],
                "tables": [],
                "multimodal_content": {}
            }
    
    def invoke(self, query: str) -> Dict[str, Any]:
        """
        执行多模态搜索
        
        Args:
            query: 搜索查询
            
        Returns:
            包含文本、图像和表格结果的字典
        """
        return self._call_mcp_search(query)


# 全局多模态搜索工具实例
multimodal_search_tool = MultimodalSearchTool()